package com.sms.service.impl;

import com.sms.exception.DataFileCorruptedException;
import com.sms.exception.SMSException;
import com.sms.model.Course;
import com.sms.service.CourseService;
import com.sms.util.FileUtil;
import com.sms.util.ValidateUtil;

import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import static com.sms.constants.SystemConstants.COURSE_FILE;

public class CourseServiceImpl implements CourseService {

    @Override
    public void addCourse(Course course) throws SMSException, DataFileCorruptedException {
        // 参数校验
        if (course == null) {
            throw new SMSException("课程对象不能为null");
        }
        
        if (!course.isValid()) {
            throw new SMSException("课程数据无效！");
        }
        
        try {
            // 检查文件是否存在
            FileUtil.createFileIfNotExists(COURSE_FILE);
            
            // 检查课程ID是否已存在
            List<Course> courses = FileUtil.loadCourses(COURSE_FILE);
            boolean exists = courses.stream()
                .anyMatch(c -> c.getCourseId().equals(course.getCourseId()));
            
            if (exists) {
                throw new SMSException("课程ID已存在: " + course.getCourseId());
            }
            
            // 追加写入文件
            FileUtil.writeLines(COURSE_FILE, List.of(course.toFileString()), true);
        } catch (IOException e) {
            throw new DataFileCorruptedException("课程数据文件操作失败: " + e.getMessage());
        }
    }

    @Override
    public boolean deleteCourse(String courseId) throws DataFileCorruptedException {
        // 参数校验
        if (!ValidateUtil.isValidCourseId(courseId)) {
            throw new DataFileCorruptedException("课程ID格式错误");
        }
        
        try {
            // 检查文件是否存在
            if (!FileUtil.fileExists(COURSE_FILE)) {
                return false;
            }
            
            // 读取所有课程
            List<Course> courses = FileUtil.loadCourses(COURSE_FILE);
            
            // 删除指定课程
            boolean removed = courses.removeIf(c -> c.getCourseId().equals(courseId));
            
            if (!removed) {
                return false;
            }
            
            // 保存回文件
            FileUtil.writeLines(COURSE_FILE, 
                courses.stream().map(Course::toFileString).collect(Collectors.toList()));
            
            return true;
        } catch (IOException e) {
            throw new DataFileCorruptedException("课程数据文件操作失败: " + e.getMessage());
        }
    }

    @Override
    public Course getCourse(String courseId) throws DataFileCorruptedException {
        // 参数校验
        if (!ValidateUtil.isValidCourseId(courseId)) {
            throw new DataFileCorruptedException("课程ID格式错误");
        }
        
        try {
            // 检查文件是否存在
            if (!FileUtil.fileExists(COURSE_FILE)) {
                return null;
            }
            
            // 读取并查找课程
            return FileUtil.loadCourses(COURSE_FILE).stream()
                .filter(c -> c.getCourseId().equals(courseId))
                .findFirst()
                .orElse(null);
        } catch (IOException e) {
            throw new DataFileCorruptedException("课程数据文件操作失败: " + e.getMessage());
        }
    }

    @Override
    public List<Course> getAllCourses() throws DataFileCorruptedException {
        try {
            // 检查文件是否存在
            if (!FileUtil.fileExists(COURSE_FILE)) {
                return Collections.emptyList();
            }
            
            // 读取并排序课程
            return FileUtil.loadCourses(COURSE_FILE).stream()
                .sorted(Comparator.comparing(Course::getCourseId))
                .collect(Collectors.toList());
        } catch (IOException e) {
            throw new DataFileCorruptedException("课程数据文件操作失败: " + e.getMessage());
        }
    }

    @Override
    public List<Course> searchCoursesByName(String keyword) throws DataFileCorruptedException {
        // 参数校验
        if (keyword == null || keyword.trim().isEmpty()) {
            throw new DataFileCorruptedException("搜索关键词不能为空");
        }
        
        try {
            // 检查文件是否存在
            if (!FileUtil.fileExists(COURSE_FILE)) {
                return Collections.emptyList();
            }
            
            // 读取并搜索课程
            String searchKey = keyword.toLowerCase();
            return FileUtil.loadCourses(COURSE_FILE).stream()
                .filter(c -> c.getCourseName().toLowerCase().contains(searchKey))
                .sorted(Comparator.comparing(Course::getCourseId))
                .collect(Collectors.toList());
        } catch (IOException e) {
            throw new DataFileCorruptedException("课程数据文件操作失败: " + e.getMessage());
        }
    }

    @Override
    public boolean existsCourse(String courseId) throws DataFileCorruptedException {
        // 参数校验
        if (!ValidateUtil.isValidCourseId(courseId)) {
            throw new DataFileCorruptedException("课程ID格式错误");
        }
        
        try {
            // 检查文件是否存在
            if (!FileUtil.fileExists(COURSE_FILE)) {
                return false;
            }
            
            // 检查课程是否存在
            return FileUtil.loadCourses(COURSE_FILE).stream()
                .anyMatch(c -> c.getCourseId().equals(courseId));
        } catch (IOException e) {
            throw new DataFileCorruptedException("课程数据文件操作失败: " + e.getMessage());
        }
    }

    @Override
    public int getCourseCount() throws DataFileCorruptedException {
        try {
            // 检查文件是否存在
            if (!FileUtil.fileExists(COURSE_FILE)) {
                return 0;
            }
            
            // 返回课程数量
            return FileUtil.loadCourses(COURSE_FILE).size();
        } catch (IOException e) {
            throw new DataFileCorruptedException("课程数据文件操作失败: " + e.getMessage());
        }
    }
}